#锁例程
import threading
# 创建一个锁对象
lock = threading.Lock()
shared_variable = 0

def increment():
    global shared_variable
    # 获取锁
    lock.acquire()
    try:
        for _ in range(100000):
            shared_variable += 1
    finally:
        # 释放锁
        lock.release()

# 创建两个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)

# 启动线程
thread1.start()
thread2.start()

# 等待线程执行完毕
thread1.join()
thread2.join()

print("共享变量的值:", shared_variable)
print('-'*50)

#信号量
import threading

# 创建一个信号量对象，允许 2 个线程同时访问
semaphore = threading.Semaphore(2)
shared_variable = 0

def increment():
    global shared_variable
    # 获取信号量
    semaphore.acquire()
    try:
        for _ in range(100000):
            shared_variable += 1
    finally:
        # 释放信号量
        semaphore.release()

# 创建三个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)
thread3 = threading.Thread(target=increment)

# 启动线程
thread1.start()
thread2.start()
thread3.start()

# 等待线程执行完毕
thread1.join()
thread2.join()
thread3.join()

print("共享变量的值:", shared_variable)
print('-'*50)

#条件变量
# import threading

# 创建一个条件变量对象
condition = threading.Condition()
shared_variable = 0

def producer():
    global shared_variable
    with condition:
        for _ in range(5):
            # 生产数据
            shared_variable += 1
            print("生产者生产了一个数据，当前数据量:", shared_variable)
            # 通知等待的线程
            condition.notify()
            # 等待一段时间
            condition.wait()

def consumer():
    global shared_variable
    with condition:
        for _ in range(5):
            # 等待数据
            condition.wait()
            # 消费数据
            print("消费者消费了一个数据，当前数据量:", shared_variable)
            shared_variable -= 1
            # 通知生产者
            condition.notify()

# 创建生产者和消费者线程
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)

# 启动线程
producer_thread.start()
consumer_thread.start()

# 等待线程执行完毕
producer_thread.join()
consumer_thread.join()

#线程池
import concurrent.futures

# 定义一个简单的任务函数
def task(n):
    print(f"Processing task {n}")
    return n * n

if __name__ == "__main__":
    # 创建一个包含 3 个线程的线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        # 提交多个任务到线程池
        future_results = [executor.submit(task, i) for i in range(5)]

        # 获取任务的结果
        for future in concurrent.futures.as_completed(future_results):
            result = future.result()
            print(f"Task result: {result}")


